-- UIWitchStatue
-- Created by cheny3 Dec/07/2015
-- 巫妖雕像

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

-- UIWitchStatue 继承自Layer
UIWitchStatue = class("UIWitchStatue", function()
    return cc.Layer:create();
end);

function UIWitchStatue.create(gridData, okFunc, iconPath, dialog, okText)
    return UIWitchStatue.new(gridData, okFunc, iconPath, dialog, okText);
end

-- 内部函数声明
local resize;

-- 构造函数
function UIWitchStatue:ctor(gridData, okFunc, iconPath, dialog, okText)
    self:setName("UIWitchStatue");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/blacksmith/WitchStatue.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.gridData = gridData;

    -- 查询建筑配置
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class) or {};
    self.title         = buildingInfo["title"];                                        -- 标题
    self.iconPath      = iconPath or getLevelItemIconPath(buildingInfo["icon"]);       -- 图标路径
    self.dialog        = dialog or BuildingBonusM.getBuildingDialog(self.gridData);    -- 对话内容
    self.okText        = okText or buildingInfo["view_text"];                          -- 确定按钮文本
    self.okFunc        = okFunc;                                                       -- 点击确定的回调函数

    -- 提交信息
    self.submited = {};

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIWitchStatue:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIWitchStatue", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIWitchStatue 界面析构清理");
            EventMgr.removeAll("UIWitchStatue");
        elseif eventType == "enter" then
            -- TODO
        end
    end);
end

-- 注册点击事件
function UIWitchStatue:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 先把选择框中脱下来的装备穿上去
            local info = self.submited or {};
            local classId = info.class_id;
            local isUnequiped = info.isUnequiped;

            if type(classId) == "number" and isUnequiped then
                DungeonActionM.go("do_equip", 0, classId);
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIWitchStatue");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_confirm");
            -- 判断是否放入装备
            local info = self.submited or {};

            -- 判断是否放入装备
            if not info.class_id then
                alert(getLocStr("need_any_equip"));
                return;
            end

            -- 判断是否触发事件
            local classId = info.class_id;
            local dbase =  DungeonM.queryElement(self.gridData.element, "dbase") or {};
            local needProperty = dbase["need_property"];

            -- 单纯关闭界面
            local function handleFunc2()
                -- 播放建筑强光特效（使用较弱的光效）
                EventMgr.fire(event.BUILDING_STRONG_LIGHT, {
                    ["pos"] = self.gridData:getPos(), ["isWeak"] = true,});

                -- 弹字提示
                local alertList = splitString(self.msg, "\n");
                splitAlert(alertList);
                closeFormByName("UIInvisibleForm");
                UIMgr.getCurrentScene():removeFormByName("UIWitchStatue");
            end

            local function handleFunc()
                -- 调用回调处理
                if type(self.okFunc) == "function" then
                    self:setVisible(false);

                    -- 播放建筑强光特效
                    EventMgr.fire(event.BUILDING_STRONG_LIGHT, {
                        ["pos"] = self.gridData:getPos(),});

                    -- 弹字提示
                    local alertList = splitString(self.msg, "\n");
                    splitAlert(alertList);
                    closeFormByName("UIInvisibleForm");

                    -- 等建筑强光播放完毕后执行事件
                    local function callback()
                        self.okFunc();
                        closeFormByName("UIWitchStatue");
                    end
                    performWithDelay(self, callback, 1.0);
                end
            end

            local effectNode = findChildByName(self.node, "CT/effect_node");
            -- 光效播放
            local function effectPlay(slimeEvent)
                -- 触发冈布奥事件
                if slimeEvent then
                    handleFunc();
                else
                    handleFunc2();
                end
            end

            -- 蒙上UIInvisibleForm
            local uiForm = UIInvisibleForm.create();
            UIMgr.getCurrentScene():addForm(uiForm);

            if type(needProperty) == "number" and needProperty ~= classId then
                -- 不是需要的物品
                DungeonActionM.go("cost_item", self.gridData:getPos(), classId);
                local itemName = ItemM.query(classId, "name");
                local desc = string.format(getLocStr("witch_statue_no_need_property"), itemName);
                self.msg = desc;
                -- 播放光效
                effectPlay();
                return;
            else
                local itemName = ItemM.query(classId, "name");
                local desc = string.format(getLocStr("witch_statue_need_property"), itemName);
                self.msg = desc;
                -- 播放光效
                effectPlay(true);
            end
        end
    end
    btnOk:addTouchEventListener(onOkClick);

    -- 注册装备点击格点击事件
    local equipGrid = findChildByName(node, "CT/submit_node/bg");
    local function onEquipClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 取出所有提交的装备的class_id
            local submitList = {};

            local info = self.submited or {};
            if type(info.class_id) == "number" then
                table.insert(submitList, info.class_id);
            end
            -- 打开装备选择界面
            -- 传入参数：通过魔神雕像方式打开
            local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_WITCH, {["index"] = 1, ["submited"] = submitList,});
            UIMgr.getCurrentScene():addForm(uiEquip);
        end
    end
    equipGrid:addTouchEventListener(onEquipClick);
end

-- 重绘
function UIWitchStatue:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 显示标题
    local title = self.title;
    local titleLabel = findChildByName(CT, "title_node/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CYAN, true);
    titleLabel:setString(title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示功能描述
    local desc = self.dialog;
    local descLabel = findChildByName(CT, "desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, desc);

    -- 显示建筑图标
    local mainIcon = findChildByName(CT, "icon");
    mainIcon:loadTexture(self.iconPath);

    -- 提交框
    local equipGrid = findChildByName(CT, "submit_node/icon");
    self.equipGrid = equipGrid;
    self:redrawEquip();

    -- 显示确定按钮
    local btnOk = findChildByName(CT, "btn_ok");
    local okText = self.okText;
    if #table.values(self.submited) > 0 then
        -- 有装备
        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    else
        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    end
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(okText);

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 重绘装备格
function UIWitchStatue:redrawEquip()
    -- 取出提交的装备的class_id
    local info = self.submited or {};
    if not info.class_id then
        -- checkAddBubbleStatus(self.equipGrid);
        self.equipGrid:setVisible(false);
        local frame = findChildByName(self.node, "CT/submit_node/bg");
        playLearnSkillHintEffect(frame, 70, 70);
    else
        local frame = findChildByName(self.node, "CT/submit_node/bg");
        frame:removeAllChildren();
        self.equipGrid:setVisible(true);
        local icon = ItemM.query(info.class_id, "icon");
        self.equipGrid:loadTexture(getItemIconPath(icon));
        self.equipGrid:stopAllActions();
    end
end

-- 工坊放入装备的回调
function UIWitchStatue:whenInputEquip(args)
    local equipId = args.classId;
    local isEquiped = args.isEquiped;
    if not equipId then
        return;
    end

    -- 记录装备id
    local submited = self.submited or {};
    submited = { ["class_id"] = equipId, ["isUnequiped"] = isEquiped, };
    self.submited = submited;

    -- 重绘装备格
    self:redraw();
end